<template>
  <div>
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon"><Collection /></el-icon>
          <div>
            <p class="breadcrumb-subtitle">工具管理 · 工具库位</p>
            <h2 class="breadcrumb-heading">工具库位列表</h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>工具管理</el-breadcrumb-item>
          <el-breadcrumb-item>工具库位</el-breadcrumb-item>
          <el-breadcrumb-item>工具库位列表</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <div class="stat-grid">
      <div
        v-for="card in overviewCards"
        :key="card.label"
        class="stat-card"
        :class="`is-${card.theme}`"
      >
        <div class="stat-card__icon">
          <el-icon><component :is="card.icon" /></el-icon>
        </div>
        <div>
          <p class="stat-card__label">{{ card.label }}</p>
          <h3 class="stat-card__value">
            {{ card.value }}
            <small v-if="card.suffix">{{ card.suffix }}</small>
          </h3>
          <span class="stat-card__meta">{{ card.subText }}</span>
        </div>
      </div>
    </div>

    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入库位编号/名称"
            clearable
            style="width: 240px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.state"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" :loading="loading" @click="handleSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="search-extra">
        <div class="search-pills">
          <span
            v-for="pill in quickStateOptions"
            :key="pill.label"
            class="search-pill"
            :class="{ 'is-active': searchForm.state === pill.value }"
            @click="handleQuickState(pill.value)"
          >
            {{ pill.label }}
          </span>
        </div>
        <div class="search-metrics">
          <span
            >当前总数：<b>{{ query.totalCount }}</b></span
          >
          <el-divider direction="vertical" border-style="dashed" />
          <span
            >启用率：<b>{{ enableRate }}%</b></span
          >
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-toolbar">
        <div class="table-toolbar__text">
          <p class="toolbar-caption">数据实时同步</p>
          <h3>工具库位数据看板</h3>
          <span
            >共有
            {{ query.totalCount || 0 }} 条记录，简洁管理启用/维护状态。</span
          >
        </div>
        <div class="toolbar-actions">
          <el-button type="success" plain @click="openDialogForAdd">
            新增 +
          </el-button>
          <el-button type="danger" plain @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </div>
      <el-divider />
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        :row-class-name="tableRowClassName"
        :empty-text="loading ? '数据加载中…' : '暂无符合条件的数据'"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="work_fixtureseatcode" label="库位编号" />
        <el-table-column prop="work_fixtureseatname" label="库位名称" />
        <el-table-column label="仓库管理员">
          <template #default="{ row }">
            {{ formatStorekeeperName(row) }}
          </template>
        </el-table-column>
        <el-table-column label="所在部门">
          <template #default="{ row }">
            {{ formatSectionName(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系方式" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="state" label="状态">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.state === 0">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" round @click="confirmDelete(scope.row.id)">
              删除
            </el-button>
            <el-button
              type="warning"
              round
              @click="openDialogForEdit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <div style="display: flex; align-items: center; gap: 8px">
          <el-button
            size="small"
            @click="gotoFirst"
            :disabled="query.Pageindex === 1"
            >首页</el-button
          >
          <el-button
            size="small"
            @click="gotoPrev"
            :disabled="query.Pageindex === 1"
            >上一页</el-button
          >
          <el-pagination
            v-model:current-page="query.Pageindex"
            v-model:page-size="query.PageSize"
            :page-sizes="[1, 5, 10, 15]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="query.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            size="small"
            @click="gotoNext"
            :disabled="query.Pageindex >= totalPages"
            >下一页</el-button
          >
          <el-button
            size="small"
            @click="gotoLast"
            :disabled="query.Pageindex >= totalPages"
            >尾页</el-button
          >
        </div>
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="820"
      class="fixtureseat-dialog"
      :close-on-click-modal="false"
    >
      <div class="dialog-highlight">
        <div class="dialog-highlight__main">
          <p class="dialog-pretitle">工具管理 · 工具库位</p>
          <h3>{{ dialogTitle }}</h3>
          <p class="dialog-subtitle">
            提前完善基础信息和负责人资料，可直接关联后续工具借还。
          </p>
        </div>
        <div class="dialog-highlight__tips">
          <span v-for="tip in createTips" :key="tip" class="tip-chip">
            <el-icon><CircleCheckFilled /></el-icon>
            {{ tip }}
          </span>
        </div>
      </div>
      <el-alert
        class="dialog-alert"
        title="提示：支持系统自动生成库位编号，选定管理员后可自动带出部门与联系方式。"
        type="success"
        :closable="false"
        show-icon
      />
      <el-form
        ref="formRef"
        class="fixtureseat-form"
        :model="formModel"
        :rules="rules"
        label-width="100px"
      >
        <div class="form-section">
          <div class="section-head">
            <div>
              <p class="section-caption">STEP 01</p>
              <h4>基础信息</h4>
              <span>填写库位编号及名称，确保唯一性</span>
            </div>
            <el-tag type="info" effect="dark">必填</el-tag>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库位编号" prop="work_fixtureseatcode">
                <div class="code-input">
                  <el-input
                    v-model="formModel.work_fixtureseatcode"
                    :disabled="isAutoCode"
                    placeholder="请输入库位编号"
                  />
                  <el-switch
                    v-model="isAutoCode"
                    inline-prompt
                    active-text="系统编号"
                    inactive-text="手动"
                    @change="handleAutoCodeToggle"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库位名称" prop="work_fixtureseatname">
                <el-input
                  v-model="formModel.work_fixtureseatname"
                  placeholder="请输入库位名称"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-head">
            <div>
              <p class="section-caption">STEP 02</p>
              <h4>负责人信息</h4>
              <span>选择仓库管理员并自动带出所属信息</span>
            </div>
            <el-tag type="success" effect="plain">自动带入</el-tag>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="仓库管理员" prop="storekeeperName">
                <div class="manager-input">
                  <el-input
                    v-model="formModel.storekeeperName"
                    placeholder="请选择仓库管理员"
                    disabled
                  />
                  <el-tooltip content="选择仓库管理员" placement="top">
                    <el-button
                      class="manager-picker-btn"
                      circle
                      type="primary"
                      :loading="managerLoading"
                      @click="openManagerDialog"
                    >
                      <el-icon><User /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在部门" prop="sectionName">
                <el-input
                  v-model="formModel.sectionName"
                  placeholder="请选择仓库管理员后自动带入"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-head">
            <div>
              <p class="section-caption">STEP 03</p>
              <h4>启用状态</h4>
              <span>确认联系方式与启用状态</span>
            </div>
            <el-tag type="warning" effect="plain">实时生效</el-tag>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone">
                <el-input
                  v-model="formModel.phone"
                  placeholder="请选择仓库管理员后自动带入"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="state">
                <el-radio-group v-model="formModel.state">
                  <el-radio :value="0">启用</el-radio>
                  <el-radio :value="1">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-head">
            <div>
              <p class="section-caption">STEP 04</p>
              <h4>备注说明</h4>
              <span>记录库位用途或特殊说明，便于追溯</span>
            </div>
            <el-tag type="info" effect="plain">选填</el-tag>
          </div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formModel.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitForm(formRef)"
            >保存</el-button
          >
          <el-button type="primary" @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button type="warning" @click="resetForm(formRef)">重置</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="managerDialogVisible"
      title="选择仓库管理员"
      width="640"
    >
      <div class="manager-search">
        <el-input
          v-model="managerKeyword"
          placeholder="请输入姓名/工号/部门关键字"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-table
        :data="filteredManagers"
        v-loading="managerLoading"
        height="360px"
      >
        <el-table-column prop="username" label="姓名" width="140" />
        <el-table-column prop="usernumber" label="工号" width="140" />
        <el-table-column prop="organname" label="部门" />
        <el-table-column prop="phone" label="联系方式" width="140" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleManagerPick(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  CircleCheckFilled,
  Collection,
  Finished,
  Histogram,
  Search,
  User,
  WarningFilled,
} from "@element-plus/icons-vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import https from "@/Http/http";
import axios from "axios";
import { onMounted, reactive, ref, computed, type Component } from "vue";

const tableData = ref<any[]>([]);
const selection = ref<any[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const loading = ref(false);

const query = reactive({
  Pageindex: 1,
  PageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

const searchForm = reactive({
  keyword: "",
  state: "",
});

const statusOptions = [
  { label: "启用", value: 0 },
  { label: "禁用", value: 1 },
];

type QuickStateValue = number | "";
const quickStateOptions = computed(() => [
  { label: "全部", value: "" as QuickStateValue },
  ...statusOptions,
]);

type OverviewCard = {
  label: string;
  value: number | string;
  suffix?: string;
  subText: string;
  icon: Component;
  theme: "primary" | "success" | "warning";
};

const enableRate = computed(() => {
  if (!tableData.value.length) return 0;
  const enabled = tableData.value.filter((item) => item.state === 0).length;
  return Math.round((enabled / tableData.value.length) * 100);
});

const overviewCards = computed<OverviewCard[]>(() => {
  const total = query.totalCount || tableData.value.length;
  const active = tableData.value.filter((item) => item.state === 0).length;
  const inactive = tableData.value.filter((item) => item.state === 1).length;
  return [
    {
      label: "库位总数",
      value: total,
      suffix: "个",
      subText: `本页展示 ${tableData.value.length} 条`,
      icon: Histogram,
      theme: "primary",
    },
    {
      label: "启用中",
      value: active,
      suffix: "个",
      subText: `启用率 ${enableRate.value}%`,
      icon: Finished,
      theme: "success",
    },
    {
      label: "维护/禁用",
      value: inactive,
      suffix: "个",
      subText: "建议定期巡检，快速排查库位",
      icon: WarningFilled,
      theme: "warning",
    },
  ];
});

const formRef = ref<FormInstance>();
const formModel = reactive({
  id: 0,
  work_fixtureseatcode: "",
  work_fixtureseatname: "",
  storekeeperId: null as number | null,
  storekeeperName: "",
  sectionId: null as number | null,
  sectionName: "",
  phone: "",
  remark: "",
  state: 0,
});
const managerMap = ref<
  Record<string, { username?: string; organname?: string; phone?: string }>
>({});
const sectionMap = ref<Record<string, string>>({});
const isAutoCode = ref(false);
const createTips = [
  "支持自动生成库位编号",
  "管理员决定部门及联系方式",
  "启用状态实时同步业务",
];

const rules = reactive<FormRules>({
  work_fixtureseatcode: [
    { required: true, message: "库位编号不可为空", trigger: "blur" },
  ],
  work_fixtureseatname: [
    { required: true, message: "库位名称不可为空", trigger: "blur" },
  ],
  storekeeperName: [
    { required: true, message: "仓库管理员不可为空", trigger: "change" },
  ],
  sectionName: [
    { required: true, message: "所在部门不可为空", trigger: "change" },
  ],
  phone: [{ required: true, message: "联系方式不可为空", trigger: "blur" }],
  state: [{ required: true, message: "状态不可为空", trigger: "change" }],
  remark: [{ required: true, message: "备注不可为空", trigger: "blur" }],
});

const toKey = (value: number | string | null | undefined) => {
  if (value === null || value === undefined || value === "") return "";
  return String(value);
};

const formatStorekeeperName = (row: any) => {
  const key = toKey(row?.storekeeperId);
  if (!key) return row?.storekeeperName || "-";
  return (
    row?.storekeeperName ||
    managerMap.value[key]?.username ||
    row?.storekeeperId ||
    "-"
  );
};

const formatSectionName = (row: any) => {
  const key = toKey(row?.sectionId);
  if (!key) return row?.sectionName || "-";
  return row?.sectionName || sectionMap.value[key] || row?.sectionId || "-";
};

const formatIncomingNumeric = (value: any): number | null => {
  if (value === null || value === undefined || value === "") return null;
  const num = typeof value === "number" ? value : Number(value);
  return Number.isFinite(num) ? num : null;
};

const fetchList = () => {
  loading.value = true;
  const params: any = {
    Pageindex: query.Pageindex,
    PageSize: query.PageSize,
    Work_fixtureseatcode: searchForm.keyword || undefined,
    Work_fixtureseatname: searchForm.keyword || undefined,
    State: searchForm.state !== "" ? searchForm.state : undefined,
  };
  https.Reads.get("/Applicae/Work_fixtureseatlist", {
    params,
  })
    .then((res) => {
      console.log(res.data);
      tableData.value = res.data.data;
      query.totalCount = res.data.totalCount;
      query.pageCount = res.data.pageCount;
    })
    .catch((error) => {
      ElMessage.error("获取工具库位列表失败，请稍后重试");
      tableData.value = [];
      query.totalCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleSearch = () => {
  query.Pageindex = 1;
  fetchList();
};

const handleQuickState = (value: QuickStateValue) => {
  if (searchForm.state === value) {
    searchForm.state = "";
  } else {
    searchForm.state = value as any;
  }
  handleSearch();
};

const handleReset = () => {
  searchForm.keyword = "";
  searchForm.state = "";
  handleSearch();
};

const handleSizeChange = (val: number) => {
  query.PageSize = val;
  query.Pageindex = 1;
  fetchList();
};

const handleCurrentChange = (val: number) => {
  query.Pageindex = val;
  fetchList();
};

const totalPages = computed(() =>
  Math.max(1, Math.ceil(query.totalCount / query.PageSize))
);
const gotoFirst = () => {
  if (query.Pageindex !== 1) {
    query.Pageindex = 1;
    fetchList();
  }
};
const gotoPrev = () => {
  if (query.Pageindex > 1) {
    query.Pageindex -= 1;
    fetchList();
  }
};
const gotoNext = () => {
  if (query.Pageindex < totalPages.value) {
    query.Pageindex += 1;
    fetchList();
  }
};
const gotoLast = () => {
  if (query.Pageindex !== totalPages.value) {
    query.Pageindex = totalPages.value;
    fetchList();
  }
};

const handleSelectionChange = (rows: any[]) => {
  selection.value = rows;
};

const tableRowClassName = ({ row }: { row: { state?: number } }) =>
  row?.state === 1 ? "table-row--disabled" : "";

const openDialogForAdd = () => {
  dialogTitle.value = "新增工具库位";
  resetFormValues();
  isAutoCode.value = false;
  dialogVisible.value = true;
};

const openDialogForEdit = (row: any) => {
  dialogTitle.value = "编辑工具库位";
  resetFormValues();
  formModel.id = row.id ?? 0;
  formModel.work_fixtureseatcode = row.work_fixtureseatcode ?? "";
  formModel.work_fixtureseatname = row.work_fixtureseatname ?? "";
  formModel.storekeeperId = formatIncomingNumeric(row.storekeeperId);
  formModel.storekeeperName =
    row.storekeeperName ?? row.storekeeperDisplay ?? row.storekeeperId ?? "";
  formModel.sectionId = formatIncomingNumeric(row.sectionId);
  formModel.sectionName =
    row.sectionName ?? row.sectionDisplay ?? row.sectionId ?? "";
  formModel.phone = row.phone ?? "";
  formModel.remark = row.remark ?? "";
  formModel.state = row.state ?? 0;
  ensureFormDisplayFields();
  isAutoCode.value = false;
  dialogVisible.value = true;
};

const generateSeatCode = () => {
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, "0");
  const year = now.getFullYear();
  const month = pad(now.getMonth() + 1);
  const day = pad(now.getDate());
  const hour = pad(now.getHours());
  const minute = pad(now.getMinutes());
  const second = pad(now.getSeconds());
  const ms = now.getMilliseconds().toString().padStart(3, "0");
  const random = Math.floor(Math.random() * 900 + 100);
  return `GZKW${year}${month}${day}${hour}${minute}${second}${ms}${random}`;
};

const handleAutoCodeToggle = (value: boolean) => {
  if (value) {
    formModel.work_fixtureseatcode = generateSeatCode();
  } else {
    formModel.work_fixtureseatcode = "";
  }
};

const ensureNumberId = (
  value: number | string | null | undefined
): number | undefined => {
  if (value === null || value === undefined || value === "") return undefined;
  const num = typeof value === "number" ? value : Number(value);
  return Number.isFinite(num) ? (num as number) : undefined;
};

const buildSubmitPayload = () => {
  const storekeeperId = ensureNumberId(formModel.storekeeperId);
  const sectionId = ensureNumberId(formModel.sectionId);
  return {
    id: formModel.id,
    work_fixtureseatcode: formModel.work_fixtureseatcode,
    work_fixtureseatname: formModel.work_fixtureseatname,
    storekeeperId,
    sectionId,
    phone: formModel.phone,
    remark: formModel.remark,
    state: formModel.state,
  };
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (!valid) {
      return;
    }
    const payload = buildSubmitPayload();
    if (
      payload.storekeeperId === undefined ||
      payload.sectionId === undefined
    ) {
      ElMessage.warning("请选择仓库管理员以自动带入所属信息");
      return;
    }
    if (!formModel.id) {
      https.Writes.post("/Appliance/fixtureseatAdd", payload).then(
        handleResponse
      );
    } else {
      https.Writes.put("/Appliance/fixtureseatUpdate", payload).then(
        handleResponse
      );
    }
  });
};

const handleResponse = (res: any) => {
  if (res.data.code === 1) {
    ElMessage.success(res.data.msg);
    dialogVisible.value = false;
    fetchList();
  } else {
    ElMessage.error(res.data.msg || "操作失败");
  }
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const resetFormValues = () => {
  formModel.id = 0;
  formModel.work_fixtureseatcode = "";
  formModel.work_fixtureseatname = "";
  formModel.storekeeperId = null;
  formModel.storekeeperName = "";
  formModel.sectionId = null;
  formModel.sectionName = "";
  formModel.phone = "";
  formModel.remark = "";
  formModel.state = 0;
};

const confirmDelete = (id: number) => {
  ElMessageBox.confirm("请问确认要删除吗?", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes.put("/Appliance/fixtureseatDelete", { id }).then((res) => {
        if (res.data.code === 1) {
          ElMessage.success(res.data.msg);
          fetchList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作已取消",
      });
    });
};

const handleBatchDelete = () => {
  if (!selection.value.length) {
    ElMessage.warning("请选择需要删除的工具库位！");
    return;
  }
  const ids = selection.value.map((item) => item.id);
  ElMessageBox.confirm("确认要批量删除选中的工具库位吗？", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes.delete("/Appliance/fixtureseatDeletes", {
        data: { ids },
      }).then((res) => {
        if (res.data.code === 1) {
          ElMessage.success(res.data.msg);
          fetchList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作已取消",
      });
    });
};

const managerDialogVisible = ref(false);
const managerKeyword = ref("");
const managerList = ref<any[]>([]);
const managerLoading = ref(false);

const syncManagerMaps = (list: any[]) => {
  const nextManager = { ...managerMap.value };
  const nextSection = { ...sectionMap.value };
  list.forEach((item) => {
    const managerKey = toKey(item?.id);
    if (managerKey) {
      nextManager[managerKey] = {
        username: item?.username,
        organname: item?.organname,
        phone: item?.phone,
      };
    }
    const sectionKey = toKey(item?.organid);
    if (sectionKey && item?.organname) {
      nextSection[sectionKey] = item.organname;
    }
  });
  managerMap.value = nextManager;
  sectionMap.value = nextSection;
};

const ensureFormDisplayFields = () => {
  const managerKey = toKey(formModel.storekeeperId);
  if (!formModel.storekeeperName && managerKey) {
    formModel.storekeeperName = managerMap.value[managerKey]?.username || "";
  }
  const sectionKey = toKey(formModel.sectionId);
  if (
    !formModel.sectionName &&
    (sectionKey || (managerKey && managerMap.value[managerKey]?.organname))
  ) {
    formModel.sectionName =
      sectionMap.value[sectionKey] ||
      managerMap.value[managerKey]?.organname ||
      "";
  }
  if (!formModel.phone && managerKey) {
    formModel.phone = managerMap.value[managerKey]?.phone || "";
  }
};

const fetchManagers = async () => {
  if (managerLoading.value) return;
  managerLoading.value = true;
  try {
    const res = await https.Reads.get("/RBAC/ShowUser", {
      params: { pageindex: 1, pagesize: 500 },
    });
    managerList.value = res.data?.data ?? [];
    syncManagerMaps(managerList.value);
  } catch (error) {
    ElMessage.error("获取仓库管理员列表失败，请稍后重试");
  } finally {
    managerLoading.value = false;
  }
};

const filteredManagers = computed(() => {
  const keyword = managerKeyword.value.trim().toLowerCase();
  if (!keyword) return managerList.value;
  return managerList.value.filter((item: any) => {
    return ["username", "usernumber", "organname"]
      .map((key) => item[key]?.toString().toLowerCase() ?? "")
      .some((text) => text.includes(keyword));
  });
});

const openManagerDialog = () => {
  managerDialogVisible.value = true;
  if (!managerList.value.length) {
    fetchManagers();
  }
};

const handleManagerPick = (row: any) => {
  syncManagerMaps([row]);
  formModel.storekeeperId = formatIncomingNumeric(row.id) ?? null;
  formModel.storekeeperName = row.username || "";
  formModel.sectionId = formatIncomingNumeric(row.organid) ?? null;
  formModel.sectionName = row.organname || "";
  formModel.phone = row.phone || "";
  formRef.value?.validateField(["storekeeperName", "sectionName", "phone"]);
  managerDialogVisible.value = false;
};

onMounted(() => {
  fetchList();
  fetchManagers();
});
</script>

<style scoped>
.code-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.manager-input {
  display: flex;
  align-items: center;
  gap: 8px;
}
.manager-picker-btn {
  background: linear-gradient(135deg, #409eff, #36cfc9);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.35);
}
.manager-picker-btn:focus,
.manager-picker-btn:hover {
  background: linear-gradient(135deg, #36cfc9, #67c23a);
  box-shadow: 0 6px 15px rgba(54, 207, 201, 0.4);
}
.manager-picker-btn :deep(.el-icon) {
  font-size: 18px;
}

.manager-search {
  margin-bottom: 12px;
}

.fixtureseat-dialog :deep(.el-dialog__body) {
  padding: 12px 28px 4px;
  background: linear-gradient(180deg, #f9fbff 0%, #ffffff 100%);
}

.dialog-highlight {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  padding: 20px;
  border-radius: 16px;
  background: radial-gradient(circle at top left, #eef4ff, #fff);
  border: 1px solid #eff2f7;
}
.dialog-highlight__main {
  flex: 1;
}
.dialog-pretitle {
  margin: 0;
  font-size: 12px;
  letter-spacing: 0.04em;
  color: #909399;
  text-transform: uppercase;
}
.dialog-highlight__main h3 {
  margin: 4px 0;
  font-size: 22px;
  color: #1f2f3d;
}
.dialog-subtitle {
  margin: 0;
  color: #606266;
  font-size: 13px;
}
.dialog-highlight__tips {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.tip-chip {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 10px;
  border-radius: 999px;
  background: #f0faff;
  color: #409eff;
  font-size: 13px;
  font-weight: 500;
}
.tip-chip :deep(.el-icon) {
  font-size: 14px;
}

.dialog-alert {
  margin: 14px 0 20px;
  border-radius: 10px;
}

.fixtureseat-form {
  padding: 0 4px 8px;
}

.form-section {
  padding: 18px 20px 8px;
  border-radius: 14px;
  border: 1px solid #eff2f7;
  background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
  box-shadow: 0 6px 16px rgba(31, 47, 61, 0.05);
  margin-bottom: 18px;
}
.section-head {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}
.section-caption {
  margin: 0;
  font-size: 11px;
  color: #a0a7b3;
  letter-spacing: 0.18em;
}
.section-head h4 {
  margin: 4px 0;
  font-size: 16px;
  color: #303133;
}
.section-head span {
  font-size: 13px;
  color: #8b909a;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 8px 0;
}
.dialog-footer :deep(.el-button) {
  min-width: 92px;
}
</style>

<style scoped>
.search-card {
  border-radius: 12px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.stat-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
  margin: 12px 0 18px;
}
.stat-card {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px 18px;
  border-radius: 16px;
  border: 1px solid #eef1f6;
  background: #fff;
  box-shadow: 0 8px 18px rgba(31, 47, 61, 0.06);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 24px rgba(31, 47, 61, 0.12);
}
.stat-card__icon {
  width: 46px;
  height: 46px;
  border-radius: 14px;
  display: grid;
  place-items: center;
  font-size: 22px;
  color: #fff;
}
.stat-card__label {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
.stat-card__value {
  margin: 2px 0;
  font-size: 26px;
  font-weight: 600;
  color: #2d3a4a;
}
.stat-card__value small {
  margin-left: 4px;
  font-size: 14px;
  color: #909399;
}
.stat-card__meta {
  font-size: 12px;
  color: #a0a7b3;
}
.stat-card.is-primary .stat-card__icon {
  background: linear-gradient(135deg, #7f9dff, #5c73ff);
}
.stat-card.is-success .stat-card__icon {
  background: linear-gradient(135deg, #5be7a9, #33c28b);
}
.stat-card.is-warning .stat-card__icon {
  background: linear-gradient(135deg, #ffcc80, #ff9f43);
}

.search-actions {
  display: flex;
  gap: 8px;
}

.search-extra {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}
.search-pills {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.search-pill {
  padding: 6px 16px;
  border-radius: 999px;
  border: 1px dashed #d9e2f3;
  font-size: 12px;
  color: #8190a5;
  cursor: pointer;
  transition: all 0.2s ease;
}
.search-pill.is-active {
  border-color: transparent;
  color: #fff;
  background: linear-gradient(120deg, #409eff, #36cfc9);
  box-shadow: 0 6px 14px rgba(64, 158, 255, 0.25);
}
.search-metrics {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 13px;
  color: #606266;
}
.search-metrics b {
  font-size: 16px;
  margin-left: 4px;
  color: #303133;
}

.table-card {
  border-radius: 12px;
}
.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}
.table-toolbar__text h3 {
  margin: 4px 0;
  font-size: 18px;
  color: #1f2f3d;
}
.table-toolbar__text span {
  font-size: 13px;
  color: #909399;
}
.toolbar-caption {
  margin: 0;
  font-size: 11px;
  letter-spacing: 0.2em;
  color: #a8b1c4;
  text-transform: uppercase;
}
.toolbar-actions {
  display: flex;
  gap: 10px;
}
.table-card :deep(.el-divider) {
  margin: 16px 0 12px;
}
.table-card :deep(.table-row--disabled td) {
  background: #fff7f0 !important;
  color: #a29f9c;
}
.table-card :deep(.table-row--disabled td .el-tag) {
  background: #ffe2cf;
  color: #e2842c;
  border-color: transparent;
}
.table-card :deep(.el-table__empty-text) {
  color: #a0a7b3;
}
.breadcrumb-card {
  border-radius: 12px;
  background: linear-gradient(135deg, #f5f9ff, #ffffff);
  margin-bottom: 8px;
}
.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}
.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 12px;
}
.breadcrumb-icon {
  font-size: 28px;
  color: #409eff;
}
.breadcrumb-subtitle {
  margin: 0;
  font-size: 12px;
  color: #909399;
}
.breadcrumb-heading {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}
.table-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style>
